package com.file.video;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/5/4 0:21
 * @since JDK 1.8
 */
public class VideoImageCutUtils {

    public  String videoImage(String filePath,String dir)  {
        try{
            //filePath :文件路径   dir：图片存放路径
            String pngPath = "";
            FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(filePath);
            ff.start();
            int ffLength = ff.getLengthInFrames();
            Frame f;
            int i = 0;
            while (i < ffLength) {
                f = ff.grabImage();
                //截取第6帧
                if((i>100) &&  (f.image != null)){
                    //生成图片的相对路径 例如：pic/uuid.png
                    pngPath = getPngPath();
                    //执行截图并放入指定位置
                    File file=new File(dir);
                    if(file.exists()){
                        doExecuteFrame(f, dir+pngPath);
                    }else {
                        file.mkdir();
                        doExecuteFrame(f, dir+pngPath);
                    }

                    break;
                }
                i++;
            }
            ff.stop();

            return dir+pngPath;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成图片的相对路径
     * @return 图片的相对路径 例：pic/1.png
     */
    private  String getPngPath(){
        return  "/"+getUUID()+".png";
    }


    /**
     * 生成唯一的uuid
     * @return uuid
     */
    private  String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }


    /**
     * 截取缩略图
     * @param f Frame
     * @param targerFilePath:封面图片存放路径
     */
    private  void doExecuteFrame(Frame f, String targerFilePath) {
        String imagemat = "png";
        if (null == f || null == f.image) {
            return;
        }
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bi = converter.getBufferedImage(f);
        File output = new File(targerFilePath);
        try {
            System.out.println(output);
            ImageIO.write(bi, imagemat, output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
